//
//  KZSheetView.swift
//  KZSwiftMoudel
//
//  Created by 朱凯 on 2018/6/22.
//  Copyright © 2018年 JooKey. All rights reserved.
//

import UIKit

enum KZSheetStyle {
    case sheet
    case alert
}

enum KZSheetBlurStyle {
    case light
    case dark
    var value: UIBlurEffectStyle {
        switch self {
        case .light:
            return UIBlurEffectStyle.light
        default:
            return UIBlurEffectStyle.dark
        }
    }
}

struct KZSheetConfig {
    
    var style: KZSheetStyle         = .sheet
    var title: String               = ""
    var subtitle: String            = ""
    var cancelButtonTitle: String   = "取消"
    var otherButtonTitles: [String] = [String]()
    
    var blurStyle: KZSheetBlurStyle = .light {
        didSet {
            if blurStyle == .light {
                titleColor = UIColor.black
                subtitleColor = UIColor.black
                cancelTitleColor = UIColor.red
                otherButtonTitleColor = UIColor.black
            } else {
                titleColor = UIColor.white
                subtitleColor = UIColor.white
                cancelTitleColor = UIColor.red
                otherButtonTitleColor = UIColor.white
            }
            
        }
    }
    var titleColor: UIColor = UIColor.black
    var titleFont: UIFont = UIFont.systemFont(ofSize: 15)
    var subtitleColor: UIColor = UIColor.black
    var subtitleFont: UIFont = UIFont.systemFont(ofSize: 13)
    var cancelTitleColor: UIColor = UIColor.red
    var cancelTitleFont: UIFont = UIFont.systemFont(ofSize: 15)
    var otherButtonTitleColor: UIColor = UIColor.black
    var otherButtonTitleFont = UIFont.systemFont(ofSize: 15)
    
}


class KZSheetView: UIControl {
    
    var cancelClickHandler: () -> Void = {}
    var otherButtonClickHandler: (Int) -> Void = {_ in}

    var config: KZSheetConfig       = KZSheetConfig() { didSet { self.setNeedsLayout() } }
    
    let blurView = UIVisualEffectView()
    
    let contentView = UIView()
    let titleLabel = UILabel()
    let subtitleLabel = UILabel()
    let cancelButton = UIButton()
    
    let seperateLayer = CAShapeLayer()
    
    deinit {
        print("sheet销毁")
    }
    
    convenience init() {
        
        self.init(frame: .zero)
    }
}

extension KZSheetView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 移除子视图，重新添加
        for subview in contentView.subviews { subview.removeFromSuperview() }
        contentView.removeFromSuperview()
        
        
        
        blurView.effect = UIBlurEffect(style: config.blurStyle.value)
        
        setupUI()
    }
    
    private func setupUI() {
        
        self.addSubview(contentView)
        
        config.style == .alert ? setupAlertUI() : setupSheetUI()

    }
    
    private func setupAlertUI() {
        
        contentView.layer.cornerRadius = 8
        contentView.layer.masksToBounds = true
        contentView.snp.remakeConstraints { (m) in
            m.width.equalTo(250)
            m.center.equalTo(self)
        }
        
        
        contentView.addSubview(blurView)
        blurView.snp.remakeConstraints { (m) in
            m.edges.equalTo(contentView)
        }
        
        titleLabel.numberOfLines = 0
        titleLabel.textColor = config.titleColor
        titleLabel.textAlignment = .center
        titleLabel.text = config.title
        titleLabel.font = config.titleFont
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (m) in
            m.left.equalTo(10)
            m.right.equalTo(-10)
            m.top.equalTo(10)
        }
        
        subtitleLabel.numberOfLines = 0
        subtitleLabel.textColor = config.subtitleColor
        subtitleLabel.textAlignment = .center
        subtitleLabel.text = config.subtitle
        subtitleLabel.font = config.subtitleFont
        contentView.addSubview(subtitleLabel)
        subtitleLabel.snp.makeConstraints { (m) in
            m.left.right.equalTo(titleLabel)
            m.top.equalTo(titleLabel.snp.bottom).offset(5)
        }
        
        cancelButton.backgroundColor = UIColor.white.withAlphaComponent(0.5)
        cancelButton.addTarget(self, action: #selector(onCancelClick), for: .touchUpInside)
        cancelButton.setTitle(config.cancelButtonTitle, for: .normal)
        cancelButton.setTitleColor(config.cancelTitleColor, for: .normal)
        cancelButton.titleLabel?.font = config.cancelTitleFont
        contentView.addSubview(cancelButton)
        
        if config.otherButtonTitles.count == 1 {
            
            let button = UIButton()
            button.tag = 0
            button.addTarget(self, action: #selector(onButtonClick(_:)), for: .touchUpInside)
            button.backgroundColor = UIColor.white.withAlphaComponent(0.5)
            button.setTitle(config.otherButtonTitles.first!, for: .normal)
            button.setTitleColor(config.otherButtonTitleColor, for: .normal)
            button.titleLabel?.font = config.otherButtonTitleFont
            contentView.addSubview(button)
            
            
            cancelButton.snp.makeConstraints { (m) in
                m.top.equalTo(subtitleLabel.snp.bottom).offset(10)
                m.left.equalTo(0)
                m.right.equalTo(contentView.snp.centerX).offset(-1)
                m.height.equalTo(30)
            }
            button.snp.makeConstraints { (m) in
                m.top.width.equalTo(cancelButton)
                m.right.equalTo(0)
                m.left.equalTo(contentView.snp.centerX).offset(1)
            }
        } else {
            var last: UIButton? = nil
            for (i, text) in config.otherButtonTitles.enumerated() {
                let button = UIButton()
                button.tag = i
                button.backgroundColor = UIColor.white.withAlphaComponent(0.5)
                button.addTarget(self, action: #selector(onButtonClick(_:)), for: .touchUpInside)
                button.setTitle(text, for: .normal)
                button.setTitleColor(config.otherButtonTitleColor, for: .normal)
                button.titleLabel?.font = config.otherButtonTitleFont
                contentView.addSubview(button)
                
                button.snp.makeConstraints { (m) in
                    m.left.right.equalTo(0)
                    if let last = last {
                        m.top.equalTo(last.snp.bottom).offset(2)
                    } else {
                        m.top.equalTo(subtitleLabel.snp.bottom).offset(10)
                    }
                    m.height.equalTo(30)
                }
                
                last = button
            }
            
            cancelButton.snp.makeConstraints { (m) in
                if let last = last {
                    m.top.equalTo(last.snp.bottom).offset(2)
                } else {
                    m.top.equalTo(subtitleLabel.snp.bottom).offset(10)
                }
                m.left.equalTo(0)
                m.right.equalTo(0)
                m.height.equalTo(30)
            }
        }
        
        
        
        cancelButton.snp.makeConstraints { (m) in
            m.bottom.equalTo(0)
        }
        

    }
    
    private func setupSheetUI() {
    
        contentView.layer.cornerRadius = 8
        contentView.layer.masksToBounds = true
        contentView.snp.remakeConstraints { (m) in
            m.left.equalTo(10)
            m.right.equalTo(-10)
            m.bottom.equalTo(-10)
        }
        contentView.addSubview(blurView)
        blurView.snp.remakeConstraints { (m) in
            m.edges.equalTo(contentView)
        }
        
        titleLabel.numberOfLines = 0
        titleLabel.textColor = config.titleColor
        titleLabel.textAlignment = .center
        titleLabel.text = config.title
        titleLabel.font = config.titleFont
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (m) in
            m.left.equalTo(10)
            m.right.equalTo(-10)
            m.top.equalTo(10)
        }
        
        subtitleLabel.numberOfLines = 0
        subtitleLabel.textColor = config.subtitleColor
        subtitleLabel.textAlignment = .center
        subtitleLabel.text = config.subtitle
        subtitleLabel.font = config.subtitleFont
        contentView.addSubview(subtitleLabel)
        subtitleLabel.snp.makeConstraints { (m) in
            m.left.right.equalTo(titleLabel)
            m.top.equalTo(titleLabel.snp.bottom).offset(5)
        }
        
        cancelButton.backgroundColor = UIColor.white.withAlphaComponent(0.5)
        cancelButton.addTarget(self, action: #selector(onCancelClick), for: .touchUpInside)
        cancelButton.setTitle(config.cancelButtonTitle, for: .normal)
        cancelButton.setTitleColor(config.cancelTitleColor, for: .normal)
        cancelButton.titleLabel?.font = config.cancelTitleFont
        contentView.addSubview(cancelButton)
        
        
        var last: UIButton? = nil
        for (i, text) in config.otherButtonTitles.enumerated() {
            let button = UIButton()
            button.tag = i
            button.backgroundColor = UIColor.white.withAlphaComponent(0.5)
            button.addTarget(self, action: #selector(onButtonClick(_:)), for: .touchUpInside)
            button.setTitle(text, for: .normal)
            button.setTitleColor(config.otherButtonTitleColor, for: .normal)
            button.titleLabel?.font = config.otherButtonTitleFont
            contentView.addSubview(button)
            
            button.snp.makeConstraints { (m) in
                m.left.right.equalTo(0)
                if let last = last {
                    m.top.equalTo(last.snp.bottom).offset(2)
                } else {
                    m.top.equalTo(subtitleLabel.snp.bottom).offset(10)
                }
                m.height.equalTo(30)
            }
            
            last = button
        }
        
        cancelButton.snp.makeConstraints { (m) in
            if let last = last {
                m.top.equalTo(last.snp.bottom).offset(2)
            } else {
                m.top.equalTo(subtitleLabel.snp.bottom).offset(10)
            }
            m.left.equalTo(0)
            m.right.equalTo(0)
            m.height.equalTo(30)
            
            m.bottom.equalTo(0)
        }
    }
}

// MARK: ------ 事件
extension KZSheetView {
    
    func show() {
    
        // 窗口
        let window = (UIApplication.shared.delegate as! AppDelegate).window!
        
        // 把自身添加到window上
        window.addSubview(self)
        
        self.snp.makeConstraints { (m) in
            m.edges.equalTo(window)
        }
//        window.layoutIfNeeded()
        
        if config.style == .alert {
            contentView.transform = CGAffineTransform.init(scaleX: 0.01, y: 0.01)
        } else {
            contentView.transform = CGAffineTransform.init(translationX: 0, y: 200)
        }
        
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: [], animations: {
        
            self.contentView.transform = CGAffineTransform.identity
            
        }) { (fin) in
            if fin {
                
            }
        }
    }
    
    // 消失
    @objc func dismiss() {
        
        UIView.animate(withDuration: 0.25, animations: {
            
            if self.config.style == .alert {
                self.contentView.transform = CGAffineTransform.init(scaleX: 0.01, y: 0.01)
            } else {
                self.contentView.transform = CGAffineTransform.init(translationX: 0, y: 200)
            }
            
        }) { (fin) in
            if fin {
                self.removeFromSuperview()
            }
        }
    }
    
    @objc func onCancelClick() {
    
        cancelClickHandler()
        dismiss()
    }
    
    
    @objc func onButtonClick(_ button: UIButton) {
        
        otherButtonClickHandler(button.tag)
        dismiss()
    }
}
